package cn.sfa.common.taglib;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.entity.system.FunctionSysCode;
import cn.sfa.entity.system.ModelSysCode;
import cn.sfa.entity.users.SaleUsersLogin;

/**
 * 
* 类名称：HeaderTag   
* 类描述：jsp页面的头部信息自定义标签类
* 创建人：lenovo   
* 创建时间：2012-2-9 上午10:23:00     
* 修改备注：  
* @version  v1.0
 */
public class IndexHeaderTag  extends TagSupport{
	 


	/**
	 * 
	 */
	private static final long serialVersionUID = 1355396206595036725L;


	Logger logger = LoggerFactory.getLogger(IndexHeaderTag.class);


	String menuId;
	
	@Override
	public int doEndTag() throws JspException {

		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {
		
		logger.info("--------------startTag--------------");
		
		String path = (String) pageContext.getRequest().getAttribute("path");
		
		String curURL = (String) pageContext.getRequest().getAttribute("curPath");
		
		SaleUsersLogin user = (SaleUsersLogin) pageContext.getSession().getAttribute("user");
		List userRole = user.getUserRoles(); //用户角色
		List<FunctionSysCode>  cacheFunction= CommonCache.getInstance().getAllFunction(); //功能缓存
		List<ModelSysCode>  cacheMode= CommonCache.getInstance().getAllModel(); //模块缓存
		String navURL = "";
		String menuURL = "";
		ModelSysCode currenMoudel = null;  //当前所在模块
		navURL = "/" + curURL.split("/")[1] + "/index"; //导航匹配 
		menuURL = curURL.substring(1, curURL.length()); //左边菜单匹配
		logger.info("menuURL:" + menuURL + "  | navURL:" + navURL);
		if ("login".equals(curURL.split("/")[2])) {// 登录的时候进行菜单初始化
			navURL = "/news/index";
		}
		
	
		//根据角色取模块
		List<ModelSysCode> userMoudle = new ArrayList();
		
		for(int j=0;j<userRole.size();j++){
			Map map = (Map)userRole.get(j);
			for(int i=0;i<cacheMode.size();i++){
				ModelSysCode ms = cacheMode.get(i);
				if(ms.getSaleRoleId().equals(map.get("roleId"))){
					userMoudle.add(ms);
				}
			}
		}
		
		//去重复模块
		for(int i=0;i<userMoudle.size()-1;i++){
			for(int j=userMoudle.size()-1;j>i;j--){
				if(userMoudle.get(i).getModuleId().equals(userMoudle.get(j).getModuleId())){
					userMoudle.remove(j);
				}
			}
		}
		
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("    <div class=\"top-header\">");
		buffer.append("        <div class=\"userinfo\">");
		buffer.append("            <img src='"+path+"/statics/images/icon-user.gif' style=\"margin-bottom: -6px; margin-right: 4px;\" /><span");
		buffer.append("                id=\"username\">"+user.getUserName()+"("+user.getLoginName()+")</span>，您好！<a href=\""+path+"/login/index/logout\">注销</a>");
		buffer.append("       		　");
		buffer.append("        </div>");
		buffer.append("    </div>");
		buffer.append("    <div class=\"container\">");
		buffer.append("        <!----------- 页面头部 ------------------>");
		buffer.append("        <div class=\"header\">");
		buffer.append("           <h1>");
		buffer.append("               <span>CRM客户关系管理系统</span>");
		buffer.append("            </h1>");
		buffer.append("            <!-----------  网站导航 ------------------>");
		buffer.append("           <ul class=\"navigation\" id=\"navigation\">");
		
		//遍历所有模块
		for(int i=0;i<userMoudle.size();i++){
			
			if(i==0){
				buffer.append("<li class=\"navli-l\">");
			}else if(i == userMoudle.size()-1){
				buffer.append("<li class=\"bgnone navli-r\">");
			}else{
				buffer.append("<li class=\"navli-m\">");
			}
			
			if("1".equals(userMoudle.get(i).getModuleLevel())){
				if(userMoudle.get(i).getDefaultUrl()!=null && userMoudle.get(i).getDefaultUrl().equals(navURL)){
					currenMoudel = userMoudle.get(i);
					buffer.append("<a href=\""+path+userMoudle.get(i).getDefaultUrl()+"\" class=\"current\"><span>"+userMoudle.get(i).getModuleName()+"</span></a>");
				}else
				buffer.append("<a href=\""+path+userMoudle.get(i).getDefaultUrl()+"\" ><span>"+userMoudle.get(i).getModuleName()+"</span></a>");
			}
			
			buffer.append("</li>");
		}
		buffer.append("            </ul>");
		buffer.append("            <div style=\"clear: both\">");
		buffer.append("            </div>");
		buffer.append("        </div>");

		buffer.append("   <!----------- 页面内容 ------------------>");
		buffer.append("    <div class=\"content\" id=\"content\">"); 
		
		
		JspWriter out = pageContext.getOut();
		 try {
			out.println(buffer);//输出到jsp页面
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		return super.doStartTag();
	}

}
